package com.gettagger.tagger.activities;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.gettager.tagger.custom.PageIndicator;
import com.gettagger.tagger.R;
import com.gettagger.tagger.dao.TaggerDataRetriever;
import com.gettagger.tagger.models.GuardianObject;
import com.gettagger.tagger.models.StudentInfoObject;
import com.gettagger.tagger.models.StudentObject;

public class ActDetails extends Activity {

	private ViewPager mMainPager;
	private PageIndicator mIndicator;
	private TextView txtContactNumber;
	private ImageView ivCall;
	private ImageView ivSMS;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.act_details);

		String contents = getIntent().getStringExtra("DETAILS");
		if (contents != null) {
			new DisplayDataTask().execute(contents);
		}

		mMainPager = (ViewPager) findViewById(R.id.details_viewPager);
		mMainPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int page) {
				mIndicator.setCurrentPage(page);
				if (page == 0) {
					ivCall.setVisibility(View.INVISIBLE);
					ivSMS.setVisibility(View.INVISIBLE);
				} else if (page == 1) {
					ivCall.setVisibility(View.VISIBLE);
					ivSMS.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// Not Used

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// Not Used

			}
		});

		mIndicator = (PageIndicator) findViewById(R.id.details_pager_indicator);
		mIndicator.setIndicatorColor(Color.WHITE);
		mIndicator.setPageCount(2);

		ivCall = (ImageView) findViewById(R.id.details_call);
		ivCall.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (txtContactNumber != null) {
					String contactNum = ""
							+ txtContactNumber.getText().toString().trim();
					String uri = "tel:" + contactNum.trim();
					Intent intent = new Intent(Intent.ACTION_CALL);
					intent.setData(Uri.parse(uri));
					startActivity(intent);
				}
			}
		});

		ivSMS = (ImageView) findViewById(R.id.details_sms);
		ivSMS.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (txtContactNumber != null) {
					String contactNum = ""
							+ txtContactNumber.getText().toString().trim();
					Intent smsIntent = new Intent(Intent.ACTION_VIEW);
					smsIntent.setType("vnd.android-dir/mms-sms");
					smsIntent.putExtra("address", ""+contactNum);
					smsIntent.putExtra("sms_body","Emergency Text via Tagger Application: ");
					startActivity(smsIntent);
				}

			}
		});

	}

	private class DisplayDataTask extends AsyncTask<String, Void, Void> {
		StudentInfoObject sInfoObj = new StudentInfoObject();
		private final ProgressDialog dialog = new ProgressDialog(
				ActDetails.this);
		private String errorMsg = "";

		protected void onPreExecute() {
			if (!this.dialog.isShowing()) {
				this.dialog.setMessage("Retrieving Data...");
				this.dialog.show();
			}
		}

		protected void onPostExecute(final Void unused) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}

			if (errorMsg.length() > 0) {
				showErrorMessage(errorMsg);
			}

			if (sInfoObj.guardian != null && sInfoObj.student != null) {
				CustomPagerAdapter adapter = new CustomPagerAdapter(
						ActDetails.this, sInfoObj);
				mMainPager.setAdapter(adapter);
			}
		}

		@Override
		protected Void doInBackground(String... arg0) {
			TaggerDataRetriever tdr = new TaggerDataRetriever();
			try {
				sInfoObj = tdr.getInfoObj(arg0[0]);

			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}
			return null;
		}
	}

	private void showErrorMessage(String errorMessage) {
		AlertDialog.Builder builder = new AlertDialog.Builder(ActDetails.this);
		builder.setIcon(0);
		builder.setTitle("Error");
		builder.setMessage(errorMessage);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private String rearrangeDateFormat(String dateString) {

		String returnString = null;
		java.util.Date date = null;
		if (dateString != null) {
			if (dateString.length() > 0) {
				try {
					date = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
							.parse(dateString);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}

		if (date != null) {
			returnString = new SimpleDateFormat("MMM d, yyyy").format(date);
		}
		return returnString;
	}

	private class CustomPagerAdapter extends PagerAdapter {

		private StudentInfoObject mDataCollection;
		private Context mContext;

		public CustomPagerAdapter(Context context, StudentInfoObject data) {
			mContext = context;
			mDataCollection = data;
		}

		public Object instantiateItem(View collection, int position) {
			LayoutInflater inflater = LayoutInflater.from(mContext);
			ScrollView scrollView = new ScrollView(mContext);

			if (position == 0) {
				scrollView = (ScrollView) inflater.inflate(
						R.layout.pager_student, null);
				StudentObject sObj = mDataCollection.student;

				String name = "" + sObj.last_name + "," + sObj.first_name + " "
						+ sObj.middle_name;
				((TextView) scrollView
						.findViewById(R.id.pager_student_txt_name)).setText(""
						+ name);
				((TextView) scrollView
						.findViewById(R.id.pager_student_txt_address))
						.setText("" + sObj.address);
				((TextView) scrollView.findViewById(R.id.pager_student_txt_age))
						.setText("" + sObj.age);
				((TextView) scrollView
						.findViewById(R.id.pager_student_txt_birthday))
						.setText("" + rearrangeDateFormat(sObj.birthday));
				((TextView) scrollView
						.findViewById(R.id.pager_student_txt_year_level))
						.setText("" + sObj.year_level);
				((TextView) scrollView
						.findViewById(R.id.pager_student_txt_school_year))
						.setText("" + sObj.school_year);
				((TextView) scrollView
						.findViewById(R.id.pager_student_txt_gender))
						.setText("" + sObj.gender);
				((TextView) scrollView
						.findViewById(R.id.pager_student_txt_last_updated))
						.setText(rearrangeDateFormat("" + sObj.last_updated));

			} else if (position == 1) {
				scrollView = (ScrollView) inflater.inflate(
						R.layout.pager_guardian, null);
				GuardianObject gObj = mDataCollection.guardian;

				String name = "" + gObj.last_name + "," + gObj.first_name + " "
						+ gObj.middle_name;
				((TextView) scrollView
						.findViewById(R.id.pager_guardian_txt_name)).setText(""
						+ name);
				((TextView) scrollView
						.findViewById(R.id.pager_guardian_txt_address))
						.setText("" + gObj.address);
				((TextView) scrollView
						.findViewById(R.id.pager_guardian_txt_age)).setText(""
						+ gObj.age);
				((TextView) scrollView
						.findViewById(R.id.pager_guardian_txt_birthday))
						.setText("" + rearrangeDateFormat(gObj.birthday));
				((TextView) scrollView
						.findViewById(R.id.pager_guardian_txt_gender))
						.setText("" + gObj.gender);
				((TextView) scrollView
						.findViewById(R.id.pager_guardian_txt_last_updated))
						.setText(rearrangeDateFormat("" + gObj.last_updated));
				txtContactNumber = (TextView) scrollView
						.findViewById(R.id.pager_guardian_txt_contactno);
				txtContactNumber.setText("" + gObj.contact_number);

			}
			((ViewPager) collection).addView(scrollView, 0);
			return scrollView;
		}

		@Override
		public int getCount() {

			return 2;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == ((View) arg1);
		}

		@Override
		public void destroyItem(ViewGroup collection, int position, Object view) {
			((ViewPager) collection).removeView((View) view);
		}

	}
}
